package ua.maxicash.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import ua.maxicash.editors.SystemUserEditor;
import ua.maxicash.service.AppService;
import ua.maxicash.service.MessageService;
import ua.maxicash.vo.Message;
import ua.maxicash.vo.SystemUser;

import javax.validation.Valid;
import java.util.Set;

@Controller
@RequestMapping(value = "/messages")
public class MessageController {

    private static final org.apache.log4j.Logger logger = org.apache.log4j.Logger
            .getLogger(MessageController.class);

    @Autowired
    MessageService messageService;

    @Autowired
    AppService appService;

     @InitBinder
    public void initBinder(WebDataBinder binder) {
        binder.registerCustomEditor(SystemUser.class, new SystemUserEditor(appService));
    }

    @RequestMapping(value = "/create", method = RequestMethod.GET)
    public String showCreateMessageForm(
            @RequestParam(value = "receiver", required = false) String receiversEmail, Model model) {

        User user = (User) SecurityContextHolder.getContext()
                .getAuthentication().getPrincipal();

        Message message = new Message();
        message.setSender(appService.getSystemUserByEmail(user.getUsername()));
        if (receiversEmail != null) {
            message.setReceiver(appService.getSystemUserByEmail(receiversEmail));

        }
        model.addAttribute(message);
        return "createMessage";
    }

    @RequestMapping(value = "/send", method = RequestMethod.POST)
    @ResponseBody
    public String[] sendMessageForm(@ModelAttribute("message") @Valid Message message, BindingResult bindingResult, Model model){

        if (bindingResult.hasErrors()) {
            return bindingResult.getSuppressedFields();
        }

        messageService.saveMessage(message);
        return new String[] {"{\"isOk\":true}"};

    }

    @RequestMapping(method = RequestMethod.GET)
    public ModelAndView showAllMessages() {
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        ModelAndView mav = new ModelAndView("messages");

        mav.addObject("amountOfSentMessages", messageService.getCountOfSentMessages(user.getUsername()));
        mav.addObject("amountOfReceivedMessages", messageService.getCountOfReceivedMessages(user.getUsername()));

        return mav;
    }

    @RequestMapping("/amountOfUnreadMessages")
    @ResponseBody
    public long getCountOfUnreadMessages() {

        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        return messageService.getCountOfUnreadMessages(user.getUsername());

    }

    @RequestMapping("/{idMessage}")
    @ResponseBody
    public Message getMessageById(@PathVariable Long idMessage, @RequestParam("markAsRead") boolean markAsRead) {

        return messageService.getMessageById(idMessage, markAsRead);

    }

    @RequestMapping("/received")
    @ResponseBody
    public Set<Message> getReceivedMessages(@RequestParam Long offset,
                                            @RequestParam Long amount) {
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        return messageService.getReceivedMessages(user.getUsername(),offset,amount);
    }

    @RequestMapping("/sent")
    @ResponseBody
    public Set<Message> getSentMessages(@RequestParam Long offset,
                                            @RequestParam Long amount) {
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        return messageService.getReceivedMessages(user.getUsername(),offset,amount);
    }


}
